//
//  NSMChooseCityViewController.m
//  EasyCar
//
//  Created by nsm on 2017/4/28.
//  Copyright © 2017年 beisheng. All rights reserved.
//

#import "NSMChooseCityViewController.h"
#import "NSMChooseCityCell.h"
#import "NSString+EX.h"
#import "AMapHelper.h"

@interface SearchResultsController : UITableViewController
@property (nonatomic, strong) NSMutableArray <CityModel *> *dataArray;
@property (nonatomic, copy) void(^didSelectedCity)(CityModel *city);
@end

@implementation SearchResultsController

- (instancetype)init {
    self = [super init];
    if (self) {
        self.tableView.tableHeaderView = [UIView new];
        self.tableView.tableFooterView = [UIView new];

//        if (@available(iOS 11.0, *)) {
//            self.tableView.contentInsetAdjustmentBehavior = UIScrollViewContentInsetAdjustmentNever;
//        }
    }
    return self;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    return _dataArray.count;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    static NSString *ID = @"SearchResultsController";
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:ID];
    if (!cell)
        cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:ID];
    cell.textLabel.text = _dataArray[indexPath.row].name;
    return cell;
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    [tableView deselectRowAtIndexPath:indexPath animated:YES];
    
    if (self.didSelectedCity)
        self.didSelectedCity(_dataArray[indexPath.row]);
}

@end


@interface NSMCityListCell : NSMTableViewCell
@end

@implementation NSMCityListCell {
    UILabel *_nameLabel;
}

- (void)setObject:(id)obj {
    CityModel *model = (CityModel *)obj;
    
    _nameLabel.text = model.name;
}

- (void)setupSubviews {
    MyLinearLayout *layout = [MyLinearLayout linearLayoutWithOrientation:MyOrientation_Vert];
    layout.mySize = CGSizeMake(kScreenWidth, 44);
    layout.backgroundColor = COLOR_4;
    layout.padding = UIEdgeInsetsMake(0, 15, 0, 15);
    layout.gravity = MyGravity_Vert_Center;
    [self.contentView addSubview:layout];
    
    MyBorderline *line = [[MyBorderline alloc] initWithColor:SEPARATOR_COLOR];
    line.headIndent = 15;
    layout.bottomBorderline = line;
    
    UILabel *label = [UILabel new];
    label.wrapContentSize = YES;
    label.font = SystemFont(15);
    label.textColor = COLOR_0;
    [layout addSubview:label];
    _nameLabel = label;
}

@end

static NSString *const kRecentCitiesKey = @"recentCities";
static NSString *const kReusableCellIdentifier = @"cityReusableCellIdentifier";

@interface NSMChooseCityViewController () <UITableViewDataSource, AMapLocationManagerDelegate, UISearchResultsUpdating, UISearchControllerDelegate> {
    UISearchController      *_searchController;
    SearchResultsController *_resultsController;
}
@property (nonatomic, strong) NSMutableArray<__kindof NSArray *> *dataArray;
@property (nonatomic, strong) NSArray *listArray;
@end

@implementation NSMChooseCityViewController

- (void)viewWillAppear:(BOOL)animated {
    [super viewWillAppear:animated];
    
    UINavigationBar *navBar = self.navigationController.navigationBar;
    [navBar setBackgroundImage:[UIImage imageWithColor:[THEME_COLOR colorWithAlphaComponent:0.98]]
                 forBarMetrics:UIBarMetricsDefault];
    [navBar setTranslucent:YES];

    return;
    // 位置管理器定位回调
    [_amapLocationManager startUpdatingLocation];
    __weak typeof(self) weakSelf = self;
    _amapHelper.cityDidChanged = ^(CityModel *city) {
        [weakSelf updateLocationCity:city];
    };
    _amapHelper.locationDidFailWithError = ^(NSError *error) {
        CityModel *city = [CityModel new];
        city.name = @"失败,请重试";
        [weakSelf updateLocationCity:city];
        
        // 根据错误码进行不同提示
    };
}

- (void)didInitialize {
    [super didInitialize];
    
    // 恢复默认
    self.edgesForExtendedLayout = UIRectEdgeAll;
    self.dataArray = @[].mutableCopy;
    
    // section_0(定位)
    CityModel *model = [CityModel modelWithJSON:@{@"id": @"173",
                                                  @"name": @"襄阳市",
                                                  @"code": @"0710"}];
//    if (!_appCache.selectedCity) {
//        _appCache.selectedCity = model;
//    }
    
    NSMutableArray *section_0 = @[model].mutableCopy;
    section_0.identifierEx = @"默认城市";
    [_dataArray addObject:section_0];
    
    // section_1(最近访问)
//    if ([_appCache.cache containsObjectForKey:kRecentCitiesKey]) {
//        NSArray *section_1 = SafeArray([_appCache.cache objectForKey:kRecentCitiesKey]);
//        section_1.identifierEx = @"最近访问";
//        if (section_1.count) [_dataArray addObject:section_1];
//    };
}

- (void)viewDidLoad {
    [super viewDidLoad];
    
    @nsm_weak(self)
//    [_appCache memoryCacheForKey:kCitiesData success:^(id responseObject) {
//        @nsm_strong(self)
//        dispatch_async(dispatch_get_global_queue(0, 0), ^{
//            NSArray *hot = [NSArray modelArrayWithClass:[CityModel class] json:responseObject[@"hot"]];
//            hot.identifierEx = @"热门城市";
//            [self.dataArray addObject:hot];
//            NSArray *list = [self convert:responseObject[@"list"]];
//            self.listArray = [self sortList:list];
//            [self.dataArray addObjectsFromArray:list];
//            dispatch_async(dispatch_get_main_queue(), ^{
//                [self.tableView reloadData];
//            });
//        });
//    } failure:nil hud:YES];
}

- (void)initSubviews {
    [super initSubviews];
    
    UIBarButtonItem *closeItem = [[UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemStop target:self action:@selector(dismissController)];
    self.navigationItem.leftBarButtonItem = closeItem;
    
    [self initSearchController];
    [self initTableView];
    
//    if (@available(iOS 11.0, *)) {
//        self.tableView.contentInsetAdjustmentBehavior = UIScrollViewContentInsetAdjustmentAutomatic;
//    } else {
//        self.automaticallyAdjustsScrollViewInsets = YES;
//    }
}

- (NSArray *)sortList:(NSArray *)array {
    NSMutableArray *resultArray = @[].mutableCopy;
    for (NSArray *list in array) {
        [resultArray addObjectsFromArray:list];
    }
    return resultArray;
}

- (NSArray *)convert:(NSArray *)list {
    NSMutableDictionary *tempDic = [NSMutableDictionary new];
    
    for (NSDictionary *dic in list) {
        NSString *character = [NSMCharacterManager chineseToPinYin:dic[@"name"]];
        CityModel *model = [CityModel modelWithJSON:dic];
        NSString *firstLetter = [character substringToIndex:1].uppercaseString;
        NSMutableArray *values = tempDic[firstLetter];
        if (values)
            [values addObject:model];
        else {
            // 是否以字母开头
            BOOL isBeginWithLetter = [firstLetter regex:NSMRegexBeginWithLetter];
            if (!isBeginWithLetter) {
                if (tempDic[@"#"]) {
                    values = tempDic[@"#"];
                    [values addObject:model];
                } else {
                    firstLetter = @"#";
                    values = @[model].mutableCopy;
                    tempDic[firstLetter] = values;
                }
            } else {
                values = @[model].mutableCopy;
                tempDic[firstLetter] = values;
            }
        }
    }
    
    // 索引下标
    NSArray *sortedArray = [tempDic.allKeys sortedArrayUsingSelector:@selector(compare:)];
    if (sortedArray.count == 0) return nil;
    
    NSMutableArray *indexArray = sortedArray.mutableCopy;
    // 将"#"放到最后,第一个为放大镜
    BOOL isLetter = [sortedArray.firstObject regex:NSMRegexBeginWithLetter];
    if (!isLetter) {
        NSString *firstLetter = indexArray.firstObject;
        [indexArray removeObjectAtIndex:0];
        [indexArray addObject:firstLetter];
    }
    
    NSMutableArray *resultArray = @[].mutableCopy;
    // 填充数据
    for (NSString *key in indexArray) {
        // 标题
        NSArray *values = tempDic[key];
        values.identifierEx = key;
        values.mark = @YES;
        [resultArray addObject:values];
    }
    return resultArray;
}

- (void)initSearchController {
    _resultsController = [SearchResultsController new];
    @nsm_weak(self)
    _resultsController.didSelectedCity = ^(CityModel *city) {
        @nsm_strong(self)
        [self dismissViewControllerAnimated:NO completion:^{
            [self didSelectCity:city];
        }];
    };
    
    _searchController = [[UISearchController alloc] initWithSearchResultsController:_resultsController];
    _searchController.delegate = self;
    _searchController.searchResultsUpdater = self;
    _searchController.hidesNavigationBarDuringPresentation = NO;
    // 去上下黑线
    _searchController.searchBar.backgroundImage = [UIImage imageWithColor:[UIColor whiteColor]];
    // 更改输入框背景颜色
    _searchController.searchBar.tintColor = SUB_TEXT_COLOR;
    _searchController.searchBar.barTintColor = COLOR_4;
    _searchController.searchBar.subviews.firstObject.subviews.lastObject
    .backgroundColor = GROUP_TABLECOLOR;
    [_searchController.searchBar sizeToFit];
}

- (void)initTableView {
    self.tableView.backgroundColor = GROUP_TABLECOLOR;
    self.tableView.height = kScreenHeight;
    self.tableView.dataSource = self;
    self.tableView.sectionHeaderHeight = 44;
    self.tableView.separatorStyle = UITableViewCellSeparatorStyleNone;
    self.tableView.tableHeaderView = _searchController.searchBar;
    self.tableView.sectionIndexColor = SUB_TEXT_COLOR;
    self.tableView.sectionIndexBackgroundColor = COLOR_4;
    self.definesPresentationContext = YES;
}

- (void)updateRecentCities:(CityModel *)city {
    if (![self.dataArray[1].identifierEx isEqual:@"最近访问"]) {
        // 新增一个
        [self.dataArray insertObject:@[] atIndex:1];
    }
    
    // 去除重复的
    NSArray *orgArray = self.dataArray[1];
    NSMutableArray *copyArray = [NSMutableArray arrayWithArray:orgArray];
    for (CityModel *obj in orgArray) {
        if ([obj.cid isEqualToString:city.cid]) {
            [copyArray removeObject:obj];
        }
    }
    [copyArray insertObject:city atIndex:0];
    
    // 得到最终的新数组
    NSArray *cutArray = [copyArray subarrayWithRange:NSMakeRange(0, MIN(3, copyArray.count))];
    cutArray.identifierEx = @"最近访问";
    
    // 此处可以不刷新.反正模态视图消失了用户看不到
    [self.dataArray replaceObjectAtIndex:1 withObject:cutArray];
    [self.tableView reloadData];

    // 保存起来
//    [_appCache.cache setObject:cutArray forKey:kRecentCitiesKey];
}

- (void)updateLocationCity:(CityModel *)city {
    [self.dataArray.firstObject replaceObjectAtIndex:0 withObject:city];
    [self.tableView reloadData];
}

#pragma mark - UITableViewDelegate
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    return self.dataArray.count;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    NSArray *sectionArray = self.dataArray[section];
    return [sectionArray.mark boolValue]? sectionArray.count: 1;
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
    NSArray *sectionArray = self.dataArray[indexPath.section];
    if ([sectionArray.mark boolValue]) {
        return 44;
    } else {
        NSInteger rows = ceil(sectionArray.count * 1.0 / ChooseCityMaxRowCount);
        return rows * (ChooseCityItemHeight + ChooseCityInnerSpacing) - ChooseCityInnerSpacing + 2;
    }
}

- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section {
    static NSString *identifier = @"tableView_header";
    UITableViewHeaderFooterView *header = [tableView dequeueReusableHeaderFooterViewWithIdentifier:identifier];
    UILabel *label = nil;
    if (!header) {
        header = [[UITableViewHeaderFooterView alloc] initWithReuseIdentifier:identifier];
        header.contentView.backgroundColor = GROUP_TABLECOLOR;
        label = [UILabel new];
        label.left = 15;
        label.tag = 250;
        label.font = [UIFont boldSystemFontOfSize:14];
        label.textColor = ChooseCityTitleColor;
        label.autoresizingMask = (UIViewAutoresizingFlexibleWidth |
                                  UIViewAutoresizingFlexibleHeight);
        [header.contentView addSubview:label];
    } else
        label = (UILabel *)[header viewWithTag:250];
    
    label.text = self.dataArray[section].identifierEx;
    
    return header;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    NSArray *sectionArray = self.dataArray[indexPath.section];
    BOOL mark = [sectionArray.mark boolValue];
    if (mark) {
        NSMCityListCell *cell = [NSMCityListCell cell:tableView];
        [cell setObject:sectionArray[indexPath.row]];
        return cell;
    } else {
        NSMChooseCityCell *cell = [NSMChooseCityCell cell:tableView];
        NSArray *sectionArray = self.dataArray[indexPath.section];
        [cell setObject:sectionArray.identifierEx?sectionArray:sectionArray[indexPath.row]];
        
        @nsm_weak(self)
        cell.actionBlock = ^(id obj) {
            @nsm_strong(self)
            [self didSelectCity:obj];
        };
        return cell;
    }
}

- (NSArray *)sectionIndexTitlesForTableView:(UITableView *)tableView {
    return [self sectionIndexTitles];
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    [tableView deselectRowAtIndexPath:indexPath animated:YES];
    
    NSArray *sectionArray = self.dataArray[indexPath.section];
    BOOL mark = [sectionArray.mark boolValue];
    if (!mark) return;
    
    [self didSelectCity:sectionArray[indexPath.row]];
}

- (void)didSelectCity:(id)obj {
    CityModel *city = (CityModel *)obj;
    if (!city) return;
    // 更新最近访问城市
    [self updateRecentCities:city];
    // 通知其他模块
    !self.didSelectedCity?:self.didSelectedCity(city);
    // 退出模态
    [self dismissViewControllerAnimated:YES completion:nil];
}

- (NSArray *)sectionIndexTitles {
    NSMutableArray *titles = @[].mutableCopy;
    for (NSArray *array in self.dataArray) {
        NSString *title = SafeString(array.identifierEx);
        title = [title substringToIndex:MIN(2, title.length)];
        [titles addObject:title];
    }
    return titles;
}

#pragma mark - UISearchControllerDelegate
- (void)updateSearchResultsForSearchController:(UISearchController *)searchController {
    // 去首尾空格
    NSString *searchText = [_searchController.searchBar.text stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceCharacterSet]];
    // 根据中间空格分割
    NSArray *searchItems = [searchText componentsSeparatedByString:@" "];
    NSMutableArray *andPredicates = [NSMutableArray new];
    for (NSString *item in searchItems) {
        NSMutableArray *subPredicates = [NSMutableArray new];
        NSExpression *lep = [NSExpression expressionForKeyPath:@"name"];
        NSExpression *rep = [NSExpression expressionForConstantValue:item];
        NSPredicate *predicate = [NSComparisonPredicate predicateWithLeftExpression:lep rightExpression:rep modifier:NSDirectPredicateModifier type:NSContainsPredicateOperatorType options:NSCaseInsensitivePredicateOption];
        [subPredicates addObject:predicate];
        
        NSCompoundPredicate *orPredicate = [NSCompoundPredicate orPredicateWithSubpredicates:subPredicates];
        [andPredicates addObject:orPredicate];
    }
    
    NSCompoundPredicate *finalPredicate = [NSCompoundPredicate andPredicateWithSubpredicates:andPredicates];
    
    [self searchWithPredicate:finalPredicate];
}

- (void)searchWithPredicate:(NSCompoundPredicate *)predicate {
    _resultsController.dataArray = [self.listArray filteredArrayUsingPredicate:predicate];
    [_resultsController.tableView reloadData];
}

- (void)dismissController {
    [self dismissViewControllerAnimated:YES completion:nil];
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
}

@end
